package com.github.caijinglong

import org.json.JSONObject
import java.io.FileInputStream
import java.nio.charset.Charset
import java.util.*
import kotlin.experimental.xor

class Handler {

    fun decode(txt: String): String {
        val dStr = Base64.getDecoder().decode(txt)
        val buf = ByteArray(dStr.size)
        dStr.forEachIndexed { index, byte ->
            buf[index] = byte xor key[index % key.length].toByte()
        }
        return buf.toString(Charset.defaultCharset())
    }

    fun encode(txt: String): String {
        val buf = ByteArray(txt.toByteArray(Charset.defaultCharset()).size)
//        println(txt.toByteArray().size)
        txt.toByteArray().forEachIndexed { index, byte ->
            //            println("index = $index byte = $byte")
            buf[index] = byte xor key[index % com.github.caijinglong.key.length].toByte()
        }
        return Base64.getEncoder().encode(buf).toString(Charset.defaultCharset())
    }

    fun getText(path: String = "./f/src.txt"): String {
        val txt = FileInputStream(path).bufferedReader().readText()
        return txt
    }

    fun getDecodeText(path: String = "./f/src.txt"): String {
        return decode(getText(path))
    }

    fun showAllProp(jsonObject: JSONObject) {
        jsonObject.toMap().forEach { k, v ->
            println("$k = $v")
        }
    }

    companion object {
        val DEBUFF_CARD = arrayListOf("Pain", "Clumsy", "Necronomicurse")

        @JvmStatic
        fun main(args: Array<String>) {
            val handler = object : SaveDataHandler{
                override var jsonObject: JSONObject = JSONObject()
            }

            handler.bind(SavedDataType.ZS.getGetter())
            val jsonObject = handler.jsonObject

            val new = "Limit Break"
            val old = "Juggernaut"
            val cards = jsonObject.getJSONArray("cards")
            cards.forEachIndexed { index, any ->
                val jsonObject1 = cards.getJSONObject(index)
                if (jsonObject1.getString("id") == old) {
                    jsonObject1.put("id", new)
                }
            }

            handler.save(SavedDataType.ZS.srcPath)
        }
    }
}